package com.jing.filter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.jing.comm.AppComm;
import com.jing.system.tags.loadresource.LoadResource;

/**
 * 图片过滤器
 * @author jing.yue
 * @version 2012/08/15 1.0.0
 */
public class ImgFilter implements Filter {

	private static final Logger logger = Logger.getLogger(ImgFilter.class);

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;

		String contextPath = request.getContextPath() + "/";
		String uri = request.getRequestURI();
		String file = null;
		if(uri.indexOf(contextPath) != -1) {
			file = AppComm.saveImageRoot + uri.substring(contextPath.length());
		}
		try {
			FileInputStream in = new FileInputStream(new File(file));
			OutputStream o = response.getOutputStream();
			int l = 0;
			byte[] buffer = new byte[4096];
			while ((l = in.read(buffer)) != -1) {
				o.write(buffer, 0, l);
			}
			o.flush();
			in.close();
			o.close();
		} catch (Exception e) {
			logger.error("ERROR: " + e.getMessage());
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		//初始化资源文件
		LoadResource.initLoadResource("loadresource.properties", "1.0");
	}

}
